package com.wzy.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wzy.server.mapper.AdminMapper;
import com.wzy.server.mapper.AdminRoleMapper;
import com.wzy.server.mapper.RoleMapper;
import com.wzy.server.mapper.SysMsgMapper;
import com.wzy.server.pojo.*;
import com.wzy.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.wzy.server.util.AssertUtil;
import com.wzy.server.util.AdminUtils;
import com.wzy.server.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wzy
 * @since 2021-04-30
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Resource
    private AdminMapper adminMapper;//调用数据库
    @Resource
    private UserDetailsService userDetailsService;//登陆
    @Resource
    private PasswordEncoder passwordEncoder;//加密密码
    @Resource
    private JwtTokenUtil jwtTokenUtil;//获取令牌
    @Value("${jwt.tokenHead}")
    private String tokenHead;//获取头部信息
    @Resource
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;//更新操作员角色

     /*
     根据用户名获取用户
      */
    @Override
    public Admin getAdminByUserName(String username) {
//                            查询一个                                     表的字段         传过来的属性值
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }

    /*
    登陆之后返回token
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
//                                              获取用户输入的验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
//               判断验证码是否为空                忽略大小写比较验证码
        if (StringUtils.isBlank(code) || !captcha.equals(code)) {
            return RespBean.error("验证码填写错误！");
        }
//登陆
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                        //为空                                  前端密码           获取的密码
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确!");
        }
//                          账户是否被禁用
        if (!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员!");
        }
//更新security登陆用户对象                                                                                               密码                 权限列表
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//                                                  放在security全局里面
        SecurityContextHolder.getContext().setAuthentication(authentication);
//生成token                                 获取token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();//返回map
        tokenMap.put("token", token);//获取token
        tokenMap.put("tokenHead", tokenHead);//获取头部信息
        return RespBean.success("登录成功", tokenMap);//返回前端token信息
    }


    /**
     * 根据用户id查询角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }


//    获取所有操作员
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(
                AdminUtils.getCurrentAdmin().getId(),keywords);
    }

//    更新操作员角色
    @Override
    @Transactional//涉及两个操作
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
//        删除角色
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
//        重新添加，更新
        Integer result = adminRoleMapper.addAdminRole(adminId, rids);
        if (rids.length==result){
            return  RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }


//    更新用户密码
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);//根据用户id获取用户
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();//加密密码
        if (encoder.matches(oldPass,admin.getPassword())){//根据用户比较旧密码是否相同
            admin.setPassword(encoder.encode(pass));//设置新密码,并且加密
            int result = adminMapper.updateById(admin);//获取结果
            if (1==result){
                return  RespBean.success("更新成功！");
            }
        }
        return RespBean.error("更新失败！");
        }


//      更新用户头像
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);//获取用户对象
        admin.setUserFace(url);
        int result = adminMapper.updateById(admin);
        if (1==result){
//            更新全局对象
            Admin principal = (Admin)authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return  RespBean.success("更新成功！",url);
        }
        return RespBean.error("更新失败！");
    }

}

